https://leetcode.com/problems/basic-calculator/
你會得到一個字串s ,這個字串是一組算式,請回傳算式計算的結果

這題比較麻煩的是它有括號需要處理,幸運的是他的字串不會出現乘除;因此,括號前面的負號是我們要煩惱的
這題的解法是用堆疊(stack),把目前累積的結果和括號前面的正負號儲存起來
等括號內的計算完成後,就把存起來的東西取出來並加在目前累積的結果
class Solution:
    def calculate(self, s: str) -> int:
        
        stack = []
        operation = '+' 
        num = 0
        ans = 0
        
        for i in range(len(s)):
            current = s[i]
            
            if current.isdigit():
                num = num * 10 + int(current)
            
            elif current in '+-':
                
                if operation == '+':
                    ans += num
                else:
                    ans -= num
                
                operation = current
                num = 0
            
            elif current == '(':
                stack.append(ans)
                stack.append(operation)
                operation = '+'
                num = 0
                ans = 0
            
            elif current == ')':
                
                if operation == '+':
                    ans += num
                else:
                    ans -= num
                
                operation = stack.pop()
                if operation == '-':
                    ans *= -1
                ans += stack.pop()
                num = 0
        
        
        if operation == '+':
            ans += num
        else:
            ans -= num
        return ans
不過這樣的程式碼不好修改成能處理乘除法
所以比較好的解答,應該是要在遇到括號時就呼叫自己(self.calculate),並個別回傳括號內的結果
今天的題目因為不用處理乘除所以還算簡單
大學剛學stack時也有練習過類似的題目
話說這兩天有颱風要來了,大家注意平安和防水囉!